package org.zhuzx.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * 硬件相关的一些变量值
 * @author zhuzx 2019年01月23日
 */
public class HardwareVariables {

	/** 当前是否运行于windows系统 */
	public static final boolean IS_RUN_ON_WINDOWS = System.getProperty("os.name").startsWith("Windows");
	
	/** 当前是否运行于本地开发机器 */
	public static final boolean IS_RUN_ON_LOCAL = IS_RUN_ON_WINDOWS &&
			Arrays.asList("zhuzexiang","zhuzx").contains(System.getProperty("user.name").toLowerCase());
	
	/** 当前机器的CPU线程数 */
	public static final int CPU_THREAD_NUM = Runtime.getRuntime().availableProcessors();
	
	/** 本机ip地址 */
	public static final String LOCAL_IP = getLocalHostLANAddress().getHostAddress();
	
	/**
	 * 获取本地地址，优先拿site-local地址。
	 * 来源于网络：https://www.cnblogs.com/starcrm/p/7071227.html
	 */
	@SuppressWarnings("rawtypes")
	private static InetAddress getLocalHostLANAddress() {
		try {
			InetAddress candidateAddress = null;
			// 遍历所有的网络接口
			for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
				NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
				// 在所有的接口下再遍历IP
				for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
					InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
					if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
						if (inetAddr.isSiteLocalAddress()) {
							// 如果是site-local地址，就是它了
							return inetAddr;
						} else if (candidateAddress == null) {
							// site-local类型的地址未被发现，先记录候选地址
							candidateAddress = inetAddr;
						}
					}
				}
			}
			if (candidateAddress != null) {
				return candidateAddress;
			}
			// 如果没有发现 non-loopback地址.只能用最次选的方案
			InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
			if (jdkSuppliedAddress == null) {
				throw new UnknownHostException(
						"The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
			}
			return jdkSuppliedAddress;
		} catch (Exception e) {
			UnknownHostException unknownHostException = new UnknownHostException(
					"Failed to determine LAN address: " + e);
			unknownHostException.initCause(e);
			throw new RuntimeException(unknownHostException);
		}
	}

}